package com.leyou.user.service;


import com.leyou.user.mapper.UserMapper;
import com.leyou.user.pojo.User;
import com.leyou.user.utile.CodecUtils;
import com.leyou.utils.NumberUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class UserService {


    @Autowired
    private UserMapper userMapper;


    @Autowired
    private AmqpTemplate amqpTemplate;


    @Autowired
    private StringRedisTemplate redisTemplate;


    static final String KEY_PREFIX = "user:code:phone:";


    static final Logger logger = LoggerFactory.getLogger(UserService.class);


    /**
     * 用户名 手机号 唯一性校验
     *
     * @param data
     * @param type
     * @return
     */
    public Boolean check(String data, Integer type) {

        User user = new User();
        switch (type) {
            case 1:
                user.setUsername(data);
                break;
            case 2:
                user.setPhone(data);
                break;
            default:
                return null;
        }

        return this.userMapper.selectCount(user) != 1;

    }


    /**
     * 发送手机验证码, 将消息发送给中间件
     *
     * @param phone
     * @return
     */
    public Boolean sendVerifyCode(String phone) {

        //自动生成随机验证码
        String code = NumberUtils.generateCode(4);

        System.out.println("验证码: " + code);

        try {
            //TODO 此处因为秘钥问题无法发送短信,暂且不作
            Map<String, String> msg = new HashMap<>();
            msg.put("phone", phone);
            msg.put("code", code);
            this.amqpTemplate.convertAndSend("ly.sms.exchange", "sms.verify.code", msg);

            //将验证码存入Redis中
            this.redisTemplate.opsForValue().set(KEY_PREFIX + phone, code, 5, TimeUnit.MINUTES);

            return true;
        } catch (Exception e) {
            logger.error("发送短信失败。phone：{}， code：{}", phone, code);
            return false;
        }
    }


    /**
     * 登录验证
     *
     * @param user
     * @param code
     * @return
     */
    public Boolean register(User user, String code) {

        //从Redis中取得验证码,判断验证码是否正确
        String key = KEY_PREFIX + user.getPhone();

        String redisCode = this.redisTemplate.opsForValue().get(key);

        if (!code.equals(redisCode)) return false;


        //执行注册流程

        user.setId(null);
        user.setCreated(new Date());

        //随机生成盐值
        String salt = CodecUtils.generateSalt();
        //保存盐值
        user.setSalt(salt);

        //对密码进行加密
        user.setPassword(CodecUtils.md5Hex(user.getPassword(), salt));

        //写入数据库
        boolean boo = this.userMapper.insertSelective(user) == 1;

        //保存成功删除redis中的数据
        if (boo) {

            try {
                this.redisTemplate.delete(key);
            } catch (Exception e) {
                logger.error("删除缓存验证码失败，code：{}", code, e);
            }

        }

        return boo;
    }


    /**
     * 用户登录
     *
     * @param username
     * @param password
     * @return
     */
    public User login(String username, String password) {

        User recode = new User();

        recode.setUsername(username);

        User user = this.userMapper.selectOne(recode);

        if (user == null) return null;

        if (!user.getPassword().equals(CodecUtils.md5Hex(password, user.getSalt()))) return null;

        return user;
    }

}
